<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @open="dialogOpen" @close="handleClose">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="item in roleIds" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  name: 'Assignrole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      checkList: [],
      roleIds: [],
      loading: false
    }
  },
  methods: {
    // 关闭时的回调
    handleClose() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = []
    },
    // 打开时的回调
    dialogOpen() {
      this.loading = true
      Promise.all([this.getRoleList(), this.getUserDetailById()]).then(() => {
        this.loading = false
      })
    },
    // 获取角色列表 循环渲染
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 1000)
      this.roleIds = rows
    },
    // 回显数据  // 获取员工已有角色
    async getUserDetailById() {
      const { data } = await reqGetUserDetailById(this.$parent.userId)
      this.checkList = data.roleIds || []
    },
    // 给员工分配角色
    async clickSubmit() {
      const res = await reqAssignRoles({ id: this.$parent.userId, roleIds: this.checkList })
      this.$message.success(res.message)
      this.handleClose()
    }
  }
}
</script>

<style>

</style>
